/**
 * Game class provides somes main methods to control the game states (such as running, start, stop,...)
 *
 *
 */
function Game(canvas, context) {
    var _map;
    var _player;
    var _keyStates = {};
    var _timer;

    var _isPause = false; // pause game
    var _lastPause = 0;

    var self = this;

    function clear() {
        context.clearRect(0, 0, canvas.width, canvas.height);
    };
    this.init = function() {
        
        canvas.onkeydown = canvas_keyDown;
        canvas.onkeyup = canvas_keyUp;
        context.textAlign = "left";
        _map = new Map(canvas.width, canvas.height);
        _isPause = false;
        this.newGame();
    };

    this.newGame = function() {
        _map.reset();
        _player = new Player(_map, 0, 100);
        draw();
        _timer = window.setInterval(update, 1000 / FPS);
        if(!_isMute) {
            soundManager.stop("theme");
            soundManager.play("music");
        } 
    };

    function draw() {
        clear();
        _map.draw(context, _player);
        _player.draw(context);
    }
    // the main game loop
    function update() {
        
        _map.update();
        _player.handleInputs(_keyStates);
        _player.isAutoMoving = true;
        // pause game
        window.onmousedown = function(e) {
            // get position of mouse
            var x = e.offsetX;
            var y = e.offsetY;

            // mouse down in canvas
            if (x >= 0 && x <= canvas.width &&
                y >= 0 && y <= canvas.height) {
                //gameReplay();
                //pauseScreen.stop();
            } else {
                _level = _map.level;                
                gamePause(_images);
            }
        }
        //menuPause(_images);
        _score = _map.scores;
        
        
        var time = (new Date()).getTime();
        var d = time - _timeStart;
        _timeStart = time;
        
        if (d < 5000) {
            context.font = "20px disney";
    		context.fillStyle = "black";
    		context.fillText("TIME: " + d, 100, 100);    
        }
        		  
        var ret = _player.update();
        if (ret) // die or 
        {
            var text1, text2;

            if (ret == 1) {
                //soundManager.stop("theme_rivio");
                if (_live > 0) {
                    // replay this level
                    _level = _map.level;
                    gameEndScreen(_images).start();
                } else {                    
                    // game over
                    _live = NUM_LIFE;
                    _level = 0;
                    gameOverScreen(_images).start();
                    $("article#save-score").slideDown("slow");
                }
            } else {
                // complete game
                if (_map.nextLevel()) {
                    soundManager.play('sound_complete');
                    winScreen(_images).start();
                    //$("article#save-score").slideDown("slow");
                } else {
                    gameFinishScreen(_images).start();
                    $("article#save-score").slideDown("slow");
                }
            }
            
            clearInterval(_timer);
            /*
            _timer = null;
            var top = canvas.height / 8;
            // draw the Game Over screen
            context.textAlign = "center";
            context.fillStyle = "black";
            context.fillRect(0, 0, canvas.width, canvas.height);
            context.font = "16px Arial";
            context.fillStyle = "white";
            context.fillText(text1, canvas.width / 2, top * 2);
            context.fillText("Scores : " + _map.scores, canvas.width / 2, top * 3);
            context.fillText(text2, canvas.width / 2, top * 4);
            context.textAlign = "left";
            context.font = "10px Arial";
            return;
            */
            return;
        }

        draw();

    }

    function canvas_keyDown(e) {
        e.preventDefault();

        // pause game
        if (e.keyCode == 90) {
            gamePause(_images);
        }

        if (AVAILABLE_KEYS.indexOf(e.keyCode) != -1) {
            _keyStates[e.keyCode] = true;
        }

    }

    function canvas_keyUp(e) {
        e.preventDefault();
        if (_keyStates[e.keyCode]) {
            _keyStates[e.keyCode] = false;
        }
    }

    function gamePause(_images) {
        // if game is pausing
        if (!_isPause) {
            _timer = clearTimeout(_timer);
            menuPause(_images);
            _isPause = true;
        }
        // pause music
        if(!_isMute) {
            soundManager.pause("music");
        }
    }

    function gameReplay() {
        _timer = window.setInterval(update, 1000 / FPS);
        if(!_isMute) {            
            soundManager.play("music");
        }
    }

    function gameReset() {
        _level = _map.level;
        _isPause = false;
        self.newGame();
        // replay sound
        if(!_isMute) {
            soundManager.stop("music");
            soundManager.play("music");
        }
    }

    // menu of when game pause

    function menuPause(_images) {
        // center of canvas
        var x = canvas.width / 2;
        var y = canvas.height / 2;
        var items = [];
        // background
        context.drawImage(_images.SCREEN_ITEMS, 345, 232, 20, 20, x - 155, y - 50, 310, 100);

        // reset button
        items[0] = new MenuItem({
            name: "reset_button",
            left: x - 135,
            top: y - 35,
            width: 70,
            height: 74,
            imageX: 468,
            imageY: 0,
            isDraw: true,
            image: _images.SCREEN_ITEMS,
            onclick: function() {
                gameReset();
                clearMenuPause(items);
            }
        });

        // add replay button
        items[1] = new MenuItem({
            name: "replay_button",
            left: x - 35,
            top: y - 35,
            width: 70,
            height: 76,
            imageX: 608,
            imageY: 0,
            isDraw: true,
            image: _images.SCREEN_ITEMS,
            onclick: function() {
                gameReplay();
                _isPause = false;
                clearMenuPause(items);
            }
        });
        // add menu button
        items[2] = new MenuItem({
            name: "menu_button",
            left: x + 75,
            top: y - 35,
            width: 70,
            height: 76,
            imageX: 538,
            imageY: 0,
            isDraw: true,
            image: _images.SCREEN_ITEMS,
            onclick: function() {
                //_game = null;
                clearMenuPause(items);
                _level = 0;
                _menuScreen.start();
            }
        });
        for (var i = 0; i < items.length; i++) {
            items[i].draw(context);
        }
        canvas.onmousemove = function(e) {
            // change the isMouseOver property of each MenuItem
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            canvas.style.cursor = 'default';

            for (var i = 0; i < items.length; i++) {
                items[i].isMouseOver = items[i].contain(x, y);
                // change the cursor type to hand
                if (items[i].isMouseOver)
                    canvas.style.cursor = 'pointer';
            }
        }

        canvas.onclick = function(e) {

            // raise the onclick event of each MenuItem when it is clicked
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;

            for (var i = 0; i < items.length; i++) {
                if (items[i].onclick && items[i].contain(x, y))
                    items[i].onclick(x, y);
            }
        };
    }

    // clear menu when game is pausing
    function clearMenuPause(items) {
        for (var item in items) {
            item = null;
            canvas.onclick = null;
            canvas.onmousemove = null;
            canvas.style.cursor = 'default';
        }
    }
}